package com.demo2do.fms.admin.web.controller.authority.user;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.fms.admin.entity.search.authority.UserSearch;
import com.demo2do.fms.admin.entity.vam.Department;
import com.demo2do.fms.admin.handler.VamHandler;
import com.demo2do.fms.admin.service.authority.OrganizationService;
import com.demo2do.fms.admin.service.authority.ResourceService;
import com.demo2do.fms.admin.service.authority.RoleService;
import com.demo2do.fms.admin.service.authority.UserService;
import com.demo2do.fms.admin.service.supplier.SupplierService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.authority.Organization;
import com.demo2do.fms.entity.authority.Resource;
import com.demo2do.fms.entity.authority.Role;
import com.demo2do.fms.entity.authority.RoleTemplate;
import com.demo2do.fms.entity.authority.User;
import com.demo2do.fms.entity.supplier.common.Supplier;

/**
 * 专属供应商用户管理
 *
 * @author Ark
 *
 */
@Controller
@RequestMapping("/fms-users")
@MenuSetting("menu-authority")
public class FmsUserController {
    
    private static final Logger logger = LoggerFactory.getLogger(FmsUserController.class);
    
    private static final RoleTemplate[] FMS_USER_ROLE_TEMPLATE = {RoleTemplate.FMS_USER};

    @Autowired
    private UserService userService;
    
    @Autowired
    private OrganizationService organizationService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private ResourceService resourceService;
    
    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    private VamHandler vamHandler;
    
    /**
     * fms_user list
     * 
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-fms-user-management")
    public ModelAndView list(Page page) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-list");
        
        int totals = userService.count(FMS_USER_ROLE_TEMPLATE);
        if (totals > 0) {
            
            List<User> users = userService.list(FMS_USER_ROLE_TEMPLATE, page.with(totals));
            modelAndView.addObject("users", users);
            modelAndView.addObject("page", page);
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * fms_user search panel
     * 
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search() {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-search");
        
        List<Organization> organizations = organizationService.listSystemOrganization();
        modelAndView.addObject("organizations", organizations);
        
        return modelAndView;
        
    }
    
    /**
     * fms_user filter
     * 
     * @param search
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-fms-user-management")
    public ModelAndView onSearch(UserSearch search, 
                                 HttpServletRequest request, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-list");
        
        search.addAuthority(FMS_USER_ROLE_TEMPLATE[0] + "%");
    
        int totals = userService.count(search);
        if (totals > 0) {
            
            List<User> users = userService.search(search, page.with(totals));
            
            modelAndView.addObject("users", users);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * create fms_user
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create() {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-create");
        
        // 1. find roles according role template
        RoleTemplate roleTemplate = RoleTemplate.FMS_USER;
        List<Role> roles = roleService.list(Arrays.asList(roleTemplate));
        modelAndView.addObject("roles", roles);
        
        // 2. list system organization
        List<Organization> organizations = organizationService.listSystemOrganization();
        modelAndView.addObject("organizations", organizations);
        
        // 3. list vam department
        List<Department> departments = vamHandler.listDepartment();
        modelAndView.addObject("departments", departments);
        
        return modelAndView;
        
    }
    
    /**
     * create fms_user
     * 
     * @param user
     * @param operator
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onCreate(User user, @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        try {

            userService.createFmsUser(user, operator);
            
            httpResult.success().message("创建专属供应商用户成功!");
            
        } catch (Exception e) {
            httpResult.fail("500").message("创建专属供应商用户失败! " + e.getMessage());
            logger.error("#onCreate() - create fms user fail, exception = [{}]", e);
        }
        
        return httpResult;
        
    }
    
    /**
     * edit fms_user
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-edit");
        
        User user = userService.load(User.class, id);
        modelAndView.addObject("user", user);
        
        if (user.isVam()) {
            List<Department> departments = vamHandler.listDepartment();
            modelAndView.addObject("departments", departments);
        }
        
        return modelAndView;
        
    }
    
    /**
     * on edit fms_user
     * 
     * @param user
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEdit(@Preloading("userId") User user, @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        try {

            userService.edit(user, operator);
            
            httpResult.success().message("修改用户成功");
            
        } catch (Exception e) {
            httpResult.fail("500").message("修改用户失败");
            logger.error("#onEdit() - edit fail, exception = [{}]", e);
        }
        
        return httpResult;
        
    }
    
    /**
     * delete fms_user panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-delete");
        
        modelAndView.addObject("id", id);
        
        return modelAndView;
        
    }
    
    /**
     * on delete fms_user
     * 
     * @param id
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onDelete(@PathVariable("id") Long id, 
                                             @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        try {

            User user = userService.load(User.class, id);
            userService.delete(user, operator);
            
            httpResult.success().message("删除用户成功");
            
        } catch (Exception e) {
            httpResult.fail("500").message("删除用户失败");
            logger.error("#onDelete() - delete fail, exception = [{}]", e);
        }
        
        return httpResult;
        
    }
    
    /**
     * reset password
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.GET)
    public ModelAndView resetPassword(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-reset-password");
        
        modelAndView.addObject("id", id);
        
        return modelAndView;
        
    }
    
    /**
     * @param id
     * @param password
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onResetPassword(@PathVariable("id") Long id,
                                                    @RequestParam("password") String password,
                                                    @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(User.class, id);
            userService.resetPassword(user, password, operator);
            
            httpResult.success().message("重置密码成功!");
            
        } catch (Exception e) {
            httpResult.fail("500").message("重置密码失败!");
            logger.error("#onResetPassword() - reset password fail, exception = [{}]", e);
        }
        
        return httpResult;
        
    }
    
    /**
     * fms_user view
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @MenuSetting("submenu-fms-user-management")
    public ModelAndView view(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-view");
        
        User user = userService.load(User.class, id);
        modelAndView.addObject("user", user);
        
        return modelAndView;
        
    }
    
    /**
     * fms_user view resources (菜单权限)
     * 
     * @param id
     * @param page
     * @return
     */
    @RequestMapping(value = "/{id}/resources", method = RequestMethod.GET)
    public ModelAndView viewResource(@PathVariable("id") Long id, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-resource-view");
        
        // 1. load user 
        User user = userService.load(User.class, id);
        modelAndView.addObject("user", user);
        
        // 2. list resource by page
        int totals = resourceService.count(user);
        if (totals > 0) {
            
            List<Resource> resources = resourceService.listByPage(Resource.class, page.with(totals));
            
            modelAndView.addObject("resources", resources);
            modelAndView.addObject("page", page);
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * fms_user view organization (运输供应商权限)
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/organizations", method = RequestMethod.GET)
    public ModelAndView viewOrganization(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-organization-view");
        
        User user = userService.load(User.class, id);
        Organization organization = organizationService.load(Organization.class, user.getOrgId());
        modelAndView.addObject("organization", organization);
        
        return modelAndView;
        
    }
    
    /**
     * fms_user view supplier (供应商管辖权限)
     * 
     * @param id
     * @param page
     * @return
     */
    @RequestMapping(value = "/{id}/suppliers", method = RequestMethod.GET)
    public ModelAndView viewSupplier(@PathVariable("id") Long id, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("authority/user/fms/fms-user-supplier-view");
        
        // 1. load user by id
        User user = userService.load(User.class, id);
        modelAndView.addObject("user", user);
        
        // 2. get supplier by supplierId
        Supplier supplier = supplierService.load(Supplier.class, user.getSupplierId());
        
        // 3. count suppliers by user
        int totals = supplierService.countSponsoredSupplier(supplier);
        if(totals > 0){
            
            // 4. list suppliers by user and page
            List<Supplier> suppliers = supplierService.listSponsoredSupplier(supplier, page.with(totals));
            
            modelAndView.addObject("suppliers", suppliers);
            modelAndView.addObject("page", page);
            
        }
        
        return modelAndView;
        
    }
    
}
